package com.gaohe.interceptor;

import com.alibaba.fastjson.JSON;
import com.gaohe.common.R;
import com.gaohe.pojo.Employee;
import com.gaohe.pojo.User;
import com.gaohe.utils.BaseContext;
import com.gaohe.utils.PathMatcher;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
@Slf4j
public class LoginInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String requestURI = request.getRequestURI();
        boolean check = PathMatcher.check(requestURI);
//        白名单放行
        if (check) {
//            log.info("白名单URL{}放行",requestURI);
            return true;
        }
//        登陆过放行
        Employee employee = (Employee) request.getSession().getAttribute("employee");
        if (employee != null) {
//            log.info("已登录，放行");
            //存于本地线程上
            BaseContext.setCurrentId(employee.getId());
            return true;
        }
        User user = (User) request.getSession().getAttribute("user");
        if (user != null) {
//            log.info("已登录，放行");
            BaseContext.setCurrentId(user.getId());
            return true;
        }

//        未放行
//        设置code值为:401
        response.setStatus(401);
        response.getWriter().write(JSON.toJSONString(R.error("NOTLOGIN")));
        return false;


    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
    }
}
